package com.godz.controller.index;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.godz.mapper.indexMyStoryMapper;
import com.godz.pojo.indexMyStory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class myStoryController {
    //我的日记
    final
    indexMyStoryMapper myStoryMapper;

    public myStoryController(indexMyStoryMapper myStoryMapper) {
        this.myStoryMapper = myStoryMapper;
    }

    @RequestMapping("/myStoryList")
    public String storyList(Model model, @RequestParam(value = "pageNow", defaultValue = "1") int pageNow) {
        //按最近时间倒序取前6条数据
        QueryWrapper<indexMyStory> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("story_date");
        Page<indexMyStory> myStoryPage = new Page<>(pageNow, 6);
        Page<indexMyStory> myStoryPage2 = myStoryMapper.selectPage(myStoryPage, wrapper);
        List<indexMyStory> List6 = myStoryPage2.getRecords();
        model.addAttribute("storyList6", List6);
        //查询总共多少页数据
        Integer countAll = myStoryMapper.selectCount(null);
        model.addAttribute("countAll", countAll);
        //查询5条最近重点事件
        QueryWrapper<indexMyStory> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("focus", 1).orderByDesc("story_date").last("limit 5");
        List<indexMyStory> myStoryImp5 = myStoryMapper.selectList(wrapper2);
        model.addAttribute("Imp5", myStoryImp5);
        //总页数
        int pageAll = (int) Math.floor(countAll / 6);
        if (pageAll == 0) {
            pageAll++;
        }
        model.addAttribute("pageNow", pageNow);
        model.addAttribute("pageAll", pageAll);

        return "indexConList";
    }

    /**
     * 跳转,翻页
     */
    @PostMapping("/myStoryList/skip")
    public String Skip(@RequestParam("skipNumber") String skipNumber) {
        return "redirect:/myStoryList?pageNow=" + skipNumber + "#blog";
    }

    /**
     * 内容详细
     */
    @RequestMapping("/myStory")
    public String story(Model model, @RequestParam(value = "id") int id) {
        QueryWrapper<indexMyStory> wrapper = new QueryWrapper<indexMyStory>().eq("id", id);
        indexMyStory myStory = myStoryMapper.selectOne(wrapper);
        indexMyStory myStory1 = new indexMyStory();
        //浏览次数+1
        Integer views = myStory.getViews();
        views++;
        //更新数据库
        myStory1.setId(id);
        myStory1.setViews(views);
        model.addAttribute("myStory", myStory);
        myStoryMapper.updateById(myStory1);
        return "indexCon";
    }

}
